package hibernate;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 使用AOP捕获插入用户时出现的字段重复异常
 */
@Aspect
@Component
public class InsertAspect {
    /**
     * 切入受Spring管理的任何软件包下的UserService类中叫做register的public方法
     */
    @Around("execution(public * *..UserService.register(..))")
    public Object doSomething(ProceedingJoinPoint pjp) throws Throwable {
        Object retVal;
        try {
            // 执行UserService.register方法
            retVal = pjp.proceed();
        } catch (jakarta.persistence.PersistenceException e) {
            if(e.getMessage().contains("org.hibernate.exception.ConstraintViolationException")) {
                System.err.println(e.getMessage());
                throw new RuntimeException("用户插入失败，可能是字段长度不匹配或者约束字段重复");
            } else {
                throw e;
            }
        }
        return retVal;
    }
}
